import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Spin, Button, Modal } from 'antd';
import EditPage from '@/components/EditPage';
// import DetailPage from '@/components/DetailPage';
import { queryDict } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import {
  allDispatchType,
  codes,
  selectArchivesDetailAndInfo,
  selectArchivesList,
  checkConfirm,
} from './utils';
import ArchivesDriverslInfo from './ArchivesDriverslInfo';
import EmptyArchivesForm from './EmptyArchivesForm';
import AdButton from '@/components/AdButton';

const { confirm } = Modal;

@connect(({ Archives, loading, component }) => ({
  Archives,
  emptyDetails: Archives.emptyDetails,
  feeData: Archives.feeData,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.selectEmptyDetails],
}))
export default class ArchivesOperateEmpty extends Component {
  constructor(props) {
    super(props);
    this.state = {
      detail: {},
      disabled: false,
    };
  }
  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.cabinetTypeHK];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
    } = this.props;
    if (id) {
      this.handleStateChange([{ detailId: id }]);
    }
  }

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  headerOperate = () => {
    const {
      match: {
        params: { id },
      },
      emptyDetails,
    } = this.props;
    const { disabled, detailId } = this.state;
    const detail = emptyDetails[detailId] || {};
    const isCONFIRM = detail.status == 'SUBMITTED' ? true : false;
    return (
      <div>
        {!disabled ? (
          <>
            <Button.Group>
              <AdButton
                text="保存"
                type="primary"
                code={codes.add}
                onClick={() => this.saveInfo('save')}
                disabled={isCONFIRM}
              />
              {id && (
                <AdButton
                  onClick={() => {
                    this.setState(preState => ({
                      disabled: !preState.disabled,
                    }));
                  }}
                  text="取消"
                  code={id ? codes.edit : codes.add}
                />
              )}
            </Button.Group>
          </>
        ) : (
          <Button.Group>
            {id && detail.status == 'UNSEALED' && (
              <AdButton
                text="审核确认"
                code={codes.confirm}
                onClick={() => this.saveInfo('confirm')}
                disabled={isCONFIRM}
              />
            )}
            {detail.status == 'CONFIRM' && (
              <>
                <AdButton
                  text="费用试算"
                  code={codes.trial}
                  onClick={() => this.saveInfo('trial')}
                  disabled={isCONFIRM}
                />
                <AdButton
                  text="提交"
                  code={codes.commit}
                  onClick={() => this.saveInfo('commit')}
                  disabled={isCONFIRM}
                />
              </>
            )}
            <AdButton
              onClick={() => {
                this.setState(preState => ({
                  disabled: !preState.disabled,
                }));
              }}
              text="编辑"
              type="primary"
              disabled={isCONFIRM}
              code={id ? codes.edit : codes.add}
            />
          </Button.Group>
        )}
      </div>
    );
  };

  onRef = ref => {
    this.child = ref;
  };

  //保存(确认、试算、提交)
  saveInfo = type => {
    if (type == 'save') {
      this.child.saveInfo();
      return;
    } else {
      const { emptyDetails } = this.props;
      const { detailId } = this.state;
      const detail = emptyDetails[detailId] || {};
      if (type == 'commit' && detail.driverBillList) {
        this.dispatchOperate({}, type);
      } else {
        this.dispatchOperate(type);
      }
    }
  };

  // 确认、试算、提交
  dispatchOperate = type => {
    const { dispatch, formValues } = this.props;
    const { detailId, isHK } = this.state;
    const id = detailId;

    const unit = {
      callDispatch: () => {
        selectArchivesDetailAndInfo({
          type: allDispatchType.selectEmptyDetails,
          payload: { id },
          props: this.props,
          callback: data => {
            if (!data) return;
            this.setState({
              recordStatus: data.status,
            });
          },
        });
        selectArchivesList({ props: this.props, payload: formValues });
      },
      callCommit: (tips = '') => {
        confirm({
          title: `${tips}提交后数据将不能进行修改，是否进行提交？`,
          content: ' ',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            dispatch({
              type: allDispatchType.commit,
              payload: { ids: [id] },
              callback: data => {
                if (!data) return;
                unit.callDispatch();
              },
            });
          },
        });
      },
    };

    if (type == 'confirm') {
      //确认
      dispatch({
        type: allDispatchType.confirm,
        payload: { id },
        callback: data => {
          unit.callDispatch(data);
        },
      });
    } else {
      //试算和提交
      dispatch({
        type: allDispatchType.trial,
        payload: { id, type },
        callback: data => {
          //试算完数据回显处理：未做
          this.setState({});
          if (type == 'commit') {
            const tips = '费用已计算，';
            unit.callCommit(tips);
          } else {
            unit.callDispatch();
          }
        },
      });
    }
  };

  render() {
    const { loading, emptyDetails } = this.props;
    const { detailId, disabled } = this.state;
    const detail = emptyDetails[detailId] || {};

    const editPageParams = {
      title: detail.archivesNo || '',
      headerOperate: this.headerOperate(),
      panelValue: [
        { key: '基础信息' },
        detail.status !== 'UNSEALED' && {
          key: '司机提成',
        },
      ],
    };

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={loading}>
          {detailId && (
            <EmptyArchivesForm
              disabled={disabled}
              onRef={this.onRef}
              detailId={detailId}
              mode="edit"
            />
          )}
        </Spin>
        {detail.status !== 'UNSEALED' && (
          <Fragment>
            <ArchivesDriverslInfo businessType="EMPTY" archivesId={detailId} isHK={true} />
          </Fragment>
        )}
      </EditPage>
    );
  }
}
